package com.wgke.bluetooth.ui;

import android.content.res.ColorStateList;
import android.text.TextUtils;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import androidx.core.content.ContextCompat;

import com.wgke.bluetooth.R;
import com.wgke.bluetooth.event.EventReadBean;
import com.wgke.bluetooth.event.EventWriteBean;
import com.wgke.bluetooth.tools.BtMsg;
import com.wgke.bluetooth.utils.ColorUtils;
import com.wgke.bluetooth.utils.CommonUtil;
import com.wgke.bluetooth.utils.ConfigurableByteArrayProcessor;
import com.wgke.bluetooth.utils.SpUtil;
import com.wgke.bluetooth.utils.ToastUtil;
import com.wgke.bluetooth.vm.ReadWriteVM;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

public class ReadWrite2Activity extends BaseListActivity<ReadWriteVM> {

    @Override
    public int layoutId() {
        return R.layout.activity_read_write2;
    }


    @Override
    public int itemId() {
        return R.layout.item_btn;
    }

    @Override
    protected void initStateBar() {
        super.initStateBar();
        initToolbar("安用服务");

    }

    @Override
    public void initOtherView() {
        String uuid = getIntent().getStringExtra("uuid");
        EditText input = findViewById(R.id.input);
        TextView readInput = findViewById(R.id.readInput);
        findViewById(R.id.sendCmd).setOnClickListener(v -> {
            String data = input.getText().toString();
            if (TextUtils.isEmpty(data) || data.trim().isEmpty()) {
                ToastUtil.showLongMsg("请输入数据");
                return;
            }
            byte[] bytes = BtMsg.hexStringToByteArray(data);
            if (bytes == null) {
                ToastUtil.showLongMsg("数据非法，HEX格式！！！");
                return;
            }
            if (!getProcessor().process(bytes)) {
                ToastUtil.showLongMsg("数据验证格式错误，请检查！！！");
                return;
            }
            vm.writeBytes(bytes);
        });
        postDelayed(1000, () -> vm.readByService(uuid));
        postDelayed(3000, () -> {
            if (!isFinishing()) {
                vm.setNotice(true);
            }
        });
        vm.list.observe(this, cmdEntities -> {
            setAdapter(cmdEntities, (h, c) -> {
                Button btn = h.getView(R.id.btnCmd);
                btn.setText(c.name);
                ColorStateList colorStateList = ContextCompat.getColorStateList(this, ColorUtils.getColor(c.name));
                btn.setBackgroundTintList(colorStateList);
                h.getView(R.id.btnCmd).setOnClickListener(v -> {
                    input.setText(c.cmd);
                    vm.writeBytes(BtMsg.hexStringToByteArray(c.cmd));
                });
            });
        });
        vm.content.observe(this, readInput::setText);
        vm.loadCmdList();
    }

    @Override
    public void onRefresh() {

    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageReadEvent(EventReadBean event) {
        vm.readBytes(event.isRead, event.bytes);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageWriteEvent(EventWriteBean event) {
        ToastUtil.showLongMsg(event.success ? "写入成功！" : "错误" + event.msg);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        vm.setNotice(false);
    }

    @Override
    public void finish() {
        super.finish();
        vm.setNotice(false);
    }

    ConfigurableByteArrayProcessor processor;

    private ConfigurableByteArrayProcessor getProcessor() {
        if (processor == null) {
            byte[] header = SpUtil.getUsePolicyHeader();
            processor = new ConfigurableByteArrayProcessor.Builder()
                    .setHeader(header[0], header[1])  // 可选，默认就是0x5A,0xA5
                    .setFooter(SpUtil.getUsePolicyFooter())              // 可选，默认就是0xAA
                    .setUseLengthField(SpUtil.getUsePolicySize())           // 禁用长度字段
                    .setUseChecksum(SpUtil.getUsePolicySum())              // 禁用校验和
                    .build(packet -> {
                        EventBus.getDefault().post(new EventReadBean(false, packet));
                    });
        }
        return processor;
    }
}
